import { Component, OnInit } from '@angular/core';

import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {Router} from "@angular/router";
import {HttpService} from "../../service/http/http.service";
import {NzMessageService} from "ng-zorro-antd/message";

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit {
  validateForm!: FormGroup;

  constructor(
    private fb: FormBuilder,
    private http:HttpService,
    private msg:NzMessageService,
    private router:Router) {

    let obj = localStorage.getItem("user");
    if (obj){
      this.http.user = JSON.parse(obj);
      this.router.navigateByUrl('/index');
    }else {
      this.router.navigateByUrl('/login');
    }
  }

  submitForm(): void {


    if (this.validateForm.valid) {
      let url = "/user/login";
      let params = this.validateForm.value;
      this.http.postBody(url,params).then((res:any)=>{
        if (res.role == 1){
          this.http.user = res;
          localStorage.setItem("user",JSON.stringify(res));
          this.router.navigateByUrl('/index');
        }else {
          this.msg.error("账号或密码错误");
        }
      }).catch(err=>{
        this.msg.error(err);
      });
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }

  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      moblie: [null, [Validators.required]],
      password: [null, [Validators.required]],
    });
  }
}
